package com.lb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 功能描述: mongdb数据库连接上下文<br>
 * @Author: Edward
 * @Date: 2021/7/3 14:54
 */
@Component
public class MongoDbContext {

  private static final Map<String, MongoDatabaseFactory> MONGO_CLIENT_DB_FACTORY_MAP = new LinkedHashMap<>();
  private static final ThreadLocal<MongoDatabaseFactory> MONGO_DB_FACTORY_THREAD_LOCAL = new ThreadLocal<>();

  @Resource
  private MongoListProperties mongoListProperties;

  public static MongoDatabaseFactory getMongoDbFactory() {
    return MONGO_DB_FACTORY_THREAD_LOCAL.get();
  }

  public static void setMongoDbFactory(String name) {
    MONGO_DB_FACTORY_THREAD_LOCAL.set(MONGO_CLIENT_DB_FACTORY_MAP.get(name));
  }

  public static void removeMongoDbFactory() {
    MONGO_DB_FACTORY_THREAD_LOCAL.remove();
  }

  @PostConstruct
  public void afterPropertiesSet() {
    if (!CollectionUtils.isEmpty(mongoListProperties.getDbList())) {
      mongoListProperties
          .getDbList()
          .forEach(
              info -> {
                MONGO_CLIENT_DB_FACTORY_MAP.put(
                    info.getDatabase(), new SimpleMongoClientDatabaseFactory(info.getUri()));
              });
    }
  }

  @Bean(name = "mongoTemplate")
  public MultiMongoTemplate dynamicMongoTemplate() {
    Iterator<MongoDatabaseFactory> iterator = MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
    return new MultiMongoTemplate(iterator.next());
  }

  @Bean(name = "mongoDbFactory")
  public MongoDatabaseFactory mongoDbFactory() {
    Iterator<MongoDatabaseFactory> iterator = MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
    return iterator.next();
  }
}